{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<small>\n",
    "Copyright (c) 2017 Andrew Glassner\n",
    "\n",
    "Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n",
    "\n",
    "The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n",
    "\n",
    "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n",
    "</small>\n",
    "\n",
    "\n",
    "\n",
    "# Deep Learning From Basics to Practice\n",
    "## by Andrew Glassner, https://dlbasics.com, http://glassner.com\n",
    "------\n",
    "## Chapter 1: Introduction to Machine Learning\n",
    "### Miscellaneous images\n",
    "\n",
    "This notebook is provided as a “behind-the-scenes” look at code used to make some of the figures in this chapter. It is still in the hacked-together form used to develop the figures, and is only lightly commented."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "from mpl_toolkits.mplot3d import Axes3D\n",
    "import numpy as np\n",
    "import math\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.preprocessing import PolynomialFeatures\n",
    "from sklearn.pipeline import make_pipeline\n",
    "import cv2\n",
    "\n",
    "import seaborn as sns ; sns.set()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Make a File_Helper for saving and loading files.\n",
    "\n",
    "save_files = True\n",
    "\n",
    "import os, sys, inspect\n",
    "current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n",
    "sys.path.insert(0, os.path.dirname(current_dir)) # path to parent dir\n",
    "from DLBasics_Utilities import File_Helper\n",
    "file_helper = File_Helper(save_files)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Rolled and unrolled data\n",
    "fig = plt.figure()\n",
    "ax = Axes3D(fig)\n",
    "\n",
    "xres = 70\n",
    "yres = 20\n",
    "zres = 70\n",
    "\n",
    "xvals = []\n",
    "yvals = []\n",
    "zvals = []\n",
    "cols = []\n",
    "for z in range(zres):\n",
    "    for y in range(yres):\n",
    "        for x in range(xres):\n",
    "            xvals.append(x)\n",
    "            yvals.append(y)\n",
    "            zvals.append(0)\n",
    "            cols.append(x)\n",
    "            \n",
    "ax.set_zticks([])\n",
    "ax.set_yticks([])\n",
    "ax.set_xticks([])\n",
    "ax.view_init(30, 50)\n",
    "ax.scatter(xvals, yvals, zvals, cmap='rainbow', c=cols, s=50)\n",
    "file_helper.save_figure('swiss-roll-1')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# The Swiss Roll data\n",
    "fig = plt.figure()\n",
    "ax = Axes3D(fig)\n",
    "\n",
    "xres = 70\n",
    "yres = 20\n",
    "zres = 70\n",
    "\n",
    "xvals = []\n",
    "yvals = []\n",
    "zvals = []\n",
    "cols = []\n",
    "for z in range(zres):\n",
    "    for y in range(yres):\n",
    "        for x in range(xres):\n",
    "            angle = math.pi*3*x/xres\n",
    "            radius = 1 - (.8 * x/xres)\n",
    "            xvals.append(radius * np.cos(angle))\n",
    "            yvals.append(y)\n",
    "            zvals.append(radius * np.sin(angle))\n",
    "            cols.append(x)\n",
    "            \n",
    "ax.set_zticks([])\n",
    "ax.set_yticks([])\n",
    "ax.set_xticks([])\n",
    "ax.view_init(30, 50)\n",
    "ax.scatter(xvals, yvals, zvals, cmap='rainbow', c=cols, s=50)\n",
    "file_helper.save_figure('swiss-roll-2')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# A line through data. \n",
    "np.random.seed(42)\n",
    "num_points = 60\n",
    "xvals = np.linspace(-10, 10, num_points)\n",
    "xvals += np.random.uniform(-4, 4, num_points)\n",
    "yvals = xvals + np.random.uniform(-10, 10, num_points)\n",
    "plt.scatter(xvals, yvals, s=30, zorder=20)\n",
    "\n",
    "model = LinearRegression(fit_intercept=True)\n",
    "lr_xvals = xvals.reshape(len(xvals), 1)\n",
    "model.fit(lr_xvals, yvals)\n",
    "\n",
    "xpred = [[-15],[15]]\n",
    "ypred = model.predict(xpred)\n",
    "plt.plot(xpred, ypred, color='red', lw=3, zorder=10)\n",
    "file_helper.save_figure('straight-fit.png')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def PolynomialRegression(degree, **kwargs):\n",
    "    return make_pipeline(PolynomialFeatures(degree),\n",
    "                        LinearRegression(**kwargs))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Show the plots for concert attendance\n",
    "np.random.seed(42)\n",
    "num_points = 9\n",
    "\n",
    "xvals = np.linspace(1.5, 4.5, num_points)\n",
    "yvals = np.sin(xvals) + np.random.uniform(-.1, .10, num_points)\n",
    "\n",
    "plt.figure(figsize=(10,3))\n",
    "plt.subplot(1, 2, 1)\n",
    "scatter_x = [xvals[i] for i in [0,1,2,4,5,6,7]]\n",
    "scatter_y = [yvals[i] for i in [0,1,2,4,5,6,7]]\n",
    "plt.scatter(scatter_x, scatter_y, s=130, color='#2277C7')\n",
    "plt.xticks(np.linspace(1.5, 4.5, 9),range(5,5+9))\n",
    "plt.xlim(1.0, 5.0)\n",
    "plt.ylim(-1.5, 1.5)\n",
    "plt.title('Measured Attendance')\n",
    "\n",
    "plt.subplot(1, 2, 2)\n",
    "\n",
    "poly_model = PolynomialRegression(3)\n",
    "pr_xvals = xvals.reshape(len(xvals), 1)\n",
    "poly_model.fit(pr_xvals, yvals)\n",
    "xpred = [[xvals[3]],[xvals[8]]]\n",
    "ypred = poly_model.predict(xpred)\n",
    "plt.scatter(scatter_x, scatter_y, color='#2277C7', s=130, zorder=20)\n",
    "\n",
    "plt.scatter(xpred[0], ypred[0], color='#C93A3F', s=130)\n",
    "plt.scatter(xpred[1], ypred[1], color='#A19423', s=130)\n",
    "plt.xticks(np.linspace(1.5, 4.5, 9),range(5,5+9))\n",
    "plt.xlim(1.0, 5.0)\n",
    "plt.ylim(-1.5, 1.5)\n",
    "plt.title('Predicted Attendance')\n",
    "\n",
    "file_helper.save_figure('concert-predictions.png')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# linear and polynomial regressions\n",
    "np.random.seed(42)\n",
    "num_points = 8\n",
    "\n",
    "xvals = np.linspace(-np.pi/2, 2.5*np.pi, num_points)\n",
    "xvals += np.random.uniform(-.3, .3, num_points)\n",
    "yvals = np.sin(xvals) + np.random.uniform(-.1, .10, num_points)\n",
    "\n",
    "plt.figure(figsize=(10,3))\n",
    "plt.subplot(1, 2, 1)\n",
    "plt.scatter(xvals, yvals, s=130, zorder=20, color='#2277C7')\n",
    "\n",
    "model = LinearRegression(fit_intercept=True)\n",
    "pr_xvals = xvals.reshape(len(xvals), 1)\n",
    "model.fit(pr_xvals, yvals)\n",
    "xpred = [[min(xvals)],[max(xvals)+0.5]]\n",
    "ypred = model.predict(xpred)\n",
    "plt.plot(xpred, ypred, color='red', lw=3, zorder=10)\n",
    "\n",
    "plt.xlim(-4, 10)\n",
    "plt.ylim(-2, 2)\n",
    "plt.title(\"Linear Regression\")\n",
    "\n",
    "plt.subplot(1, 2, 2)\n",
    "plt.scatter(xvals, yvals, s=130, zorder=20, color='#2277C7')\n",
    "poly_model = PolynomialRegression(3)\n",
    "pr_xvals = xvals.reshape(len(xvals), 1)\n",
    "poly_model.fit(pr_xvals, yvals)\n",
    "\n",
    "xpred = np.linspace(min(xvals)-0.5, max(xvals)+0.5, 1500)\n",
    "xpred = xpred.reshape(len(xpred), 1)\n",
    "ypred = poly_model.predict(xpred)\n",
    "plt.scatter(xpred, ypred, color='red', s=5, zorder=10)\n",
    "\n",
    "plt.xlim(-4, 10)\n",
    "plt.ylim(-2, 2)\n",
    "plt.title(\"Curve Regression\")\n",
    "\n",
    "file_helper.save_figure('regressions.png')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# The output of the VGG16 model is a little complicated. Each of the\n",
    "# 1000 outputs contains an index number and the associated score\n",
    "# of the prediction for that index. This index is the location of\n",
    "# the entry in the array syn_indices_list defined in syn_indices.py.\n",
    "# Those entries are strings. The index number is the line of the\n",
    "# file (or the index into that array). Then we use that string\n",
    "# as the key in a dictionary syn_words_dict stored in syn_words,\n",
    "# and the value of that dictionary item is the descriptive string\n",
    "# for that entry. These two files are just slightly python-ized\n",
    "# versions of syn_indices.txt and syn_words.txt, available from \n",
    "# the original VGG16 Caffe source at \n",
    "# http://dl.caffe.berkeleyvision.org/caffe_ilsvrc12.tar.gz \n",
    "\n",
    "input_dir = file_helper.get_input_data_dir()\n",
    "sys.path.append(input_dir)\n",
    "import VGG16_syn_indices\n",
    "import VGG16_syn_words\n",
    "\n",
    "# Use the VGG16 model (and correctly formatted weights!) from Keras\n",
    "from keras.applications.vgg16 import VGG16\n",
    "model = VGG16()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Hey VGG16, what do you think these pictures are?\n",
    "def categorize_image(img, top_number):\n",
    "    # Read in the image, and then jiggle it around to get it into\n",
    "    # the expected input format. Images may stored at any size,\n",
    "    # but they should be square to avoid stretching before classification.\n",
    "    # First, we subtract from each component so the pixels have a \n",
    "    # zero mean. We must do this because this transformation was\n",
    "    # used when the VGG16 network was trained. There were no other\n",
    "    # data transformations applied.\n",
    "    # Next, we shuffle the color order. CV2 stores a picture in BGR \n",
    "    # order, and VGG16 seems to wang RBG (neither one the conventional \n",
    "    # RGB order). There must be a CV2 function to shuffle the channels,\n",
    "    # but I couldn't find it, so I just do it manually.\n",
    "    # Then we stick an extra dimension of size 1 at the start of the\n",
    "    # image's shape to make the single image look like a batch of\n",
    "    # images, but the batch is just this one image.\n",
    "    \n",
    "    image = cv2.resize(cv2.imread(img), (224, 224)).astype(np.float32)\n",
    "    blu = image[:,:,0].copy()\n",
    "    grn = image[:,:,1].copy()\n",
    "    red = image[:,:,2].copy()\n",
    "    blu -= 103.939  # These numbers were used for the training data\n",
    "    grn -= 116.779  # used for VGG16, so we must use them, too. See \n",
    "    red -= 123.68   # https://gist.github.com/baraldilorenzo/07d7802847aaad0a35d3\n",
    "    image[:,:,0] = red\n",
    "    image[:,:,1] = blu\n",
    "    image[:,:,2] = grn\n",
    "\n",
    "    image = np.array([image])  # make it a list of 1 image\n",
    "    \n",
    "    predictions = model.predict(image)[0]\n",
    "    top_list = []\n",
    "    for i in range(top_number):\n",
    "        maxarg = np.argmax(predictions)\n",
    "        maxval = predictions[maxarg]\n",
    "        top_list.append([maxarg, maxval])\n",
    "        predictions = [i if i<maxval else -1 for i in predictions]\n",
    "    report_scores = []\n",
    "    report_names = []\n",
    "    for i in top_list:\n",
    "        n_index = VGG16_syn_indices.syn_indices_list[i[0]]\n",
    "        words = VGG16_syn_words.syn_words_dict[n_index]\n",
    "        words = words[:16]  # clip to first 16 chars\n",
    "        report_scores.append(i[1])\n",
    "        report_names.append(words)\n",
    "    return (report_scores, report_names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Our test images\n",
    "input_dir = file_helper.get_input_data_dir()\n",
    "vgg_test_images = [\n",
    "    input_dir+'/hummingbird-2139279_1920.jpg',\n",
    "    input_dir+'/teaspoon-554065_1920.jpg',\n",
    "    input_dir+'/corkscrew-1176167_1920.jpg',\n",
    "    input_dir+'/audio-1840073_1920.jpg'\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Print out the matches\n",
    "for img in vgg_test_images:\n",
    "    scores, names = categorize_image(img, 3)\n",
    "    print(\"scores=\",scores)\n",
    "    print(\"names=\",names,\"\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from matplotlib import gridspec\n",
    "def plot_results():\n",
    "    fig = plt.figure(figsize=(8, 8))\n",
    "    gs = gridspec.GridSpec(2,4, height_ratios=[2,2,1,1,1,1,1,1])\n",
    "    for i in range(4):\n",
    "        scores, names = categorize_image(vgg_test_images[i], 5)\n",
    "        fig.subplots_adjust(wspace=0.2)\n",
    "        fig.subplots_adjust(hspace=0.75)\n",
    "        img = plt.imread(vgg_test_images[i])\n",
    "        ax0 = plt.subplot(gs[2*i])\n",
    "        ax0.imshow(img)\n",
    "        plt.xticks([],[])\n",
    "        plt.yticks([],[])\n",
    "        ax1 = plt.subplot(gs[1+(2*i)])\n",
    "        xs = range(len(names))\n",
    "        ax1.bar(xs, scores, align='center')\n",
    "        plt.xticks(xs, names, rotation='-90')\n",
    "        plt.yticks([0,1], [0,1])\n",
    "        plt.tick_params(axis='x', which='major', labelsize=12)\n",
    "    file_helper.save_figure('vgg-4-up')\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "plot_results()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Evaluate some MNIST digits by building and\n",
    "# training a deep learner\n",
    "import keras\n",
    "from keras.datasets import mnist\n",
    "from keras.models import Sequential\n",
    "from keras.layers import Dense, Dropout, Flatten\n",
    "from keras.layers import Conv2D, MaxPooling2D\n",
    "from keras import backend as keras_backend\n",
    "\n",
    "# Just in case the config file isn't set up as we expect\n",
    "keras_backend.set_image_data_format('channels_last')\n",
    "\n",
    "batch_size = 128\n",
    "num_classes = 10\n",
    "num_epochs = 12\n",
    "img_rows, img_cols = 28, 28\n",
    "\n",
    "# Read and format MNIST image data\n",
    "(X_train, y_train), (X_test, y_test) = mnist.load_data()\n",
    "X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1)\n",
    "X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)\n",
    "X_train = keras_backend.cast_to_floatx(X_train)\n",
    "X_test = keras_backend.cast_to_floatx(X_test)\n",
    "X_train /= 255\n",
    "X_test /= 255\n",
    "\n",
    "# make labels one-hot\n",
    "y_train = keras.utils.to_categorical(y_train, num_classes)\n",
    "y_test = keras.utils.to_categorical(y_test, num_classes)\n",
    "\n",
    "# build a convnet, nothing fancy\n",
    "model = Sequential()\n",
    "model.add(Conv2D(32, kernel_size=(3, 3),\n",
    "                 activation='relu', \n",
    "                 input_shape=X_train[0].shape))\n",
    "model.add(Conv2D(64, (3, 3), strides=(2,2), activation='relu'))\n",
    "model.add(Dropout(0.25))\n",
    "model.add(Flatten())\n",
    "model.add(Dense(128, activation='relu'))\n",
    "model.add(Dropout(0.5))\n",
    "model.add(Dense(num_classes, activation='softmax'))\n",
    "\n",
    "model.compile(loss='categorical_crossentropy',\n",
    "              optimizer='adam',\n",
    "              metrics=['accuracy'])\n",
    "\n",
    "history = model.fit(X_train, y_train,\n",
    "          batch_size=batch_size,\n",
    "          epochs=num_epochs,\n",
    "          verbose=1,\n",
    "          validation_data=(X_test, y_test))\n",
    "score = model.evaluate(X_test, y_test, verbose=0)\n",
    "print('Test loss:', score[0])\n",
    "print('Test accuracy:', score[1])\n",
    "\n",
    "grid_x = 8\n",
    "grid_y = 3\n",
    "plt.figure(figsize=(1*grid_x, 2*grid_y))\n",
    "for y in range(grid_y):\n",
    "    for x in range(grid_x):\n",
    "        index = x + (grid_x * y)\n",
    "        plt_index = x + (grid_x * y)\n",
    "        plt.subplot(2*grid_y, grid_x, 1+plt_index)\n",
    "        img_index = index+500\n",
    "        pred_data = np.reshape(X_test[img_index], (1, 28, 28, 1))\n",
    "        pred = model.predict(pred_data, verbose=0)\n",
    "        plt.imshow(np.reshape(X_test[img_index],(28,28)),cmap='gray')\n",
    "        plt.xticks([],[])\n",
    "        plt.yticks([],[])\n",
    "        plt.title(str(np.argmax(pred)))\n",
    "plt.tight_layout()\n",
    "file_helper.save_figure('mnist-convnet-predictions')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
